/*
 *  DataBuffer.c
 *  NetTalk
 *
 *  Created by Andrey on 14/10/2008.
 *  Copyright 2008 ИУ7-2003. All rights reserved.
 *
 */

#include <stdlib.h>
#include <string.h>
#include "DataBuffer.h"

DataBuffer AllocateDataBuffer(int bufferSize)
{
	BytePtr bufferData = (BytePtr)malloc(bufferSize);
	
	DataBuffer newBuffer;
	
	newBuffer.data = bufferData;
	newBuffer.dataLength = bufferSize;
	newBuffer.currentOffset = 0;
	
	memset(bufferData, 0, bufferSize);
	
	return newBuffer;
}

DataBuffer InitDataBufferWithDataAndLength(BytePtr data, int dataLength)
{
	DataBuffer newBuffer;
	
	newBuffer.data = data;
	newBuffer.dataLength = dataLength;
	newBuffer.currentOffset = 0;
	
	return newBuffer;
}

void WriteToDataBuffer(DataBufferPtr dataBuffer, BytePtr data, int bytesToWrite)
{
	if (dataBuffer->dataLength - dataBuffer->currentOffset >= bytesToWrite)
	{
		memcpy(dataBuffer->data + dataBuffer->currentOffset, data, bytesToWrite);
		dataBuffer->currentOffset += bytesToWrite;
	}
}

DataBuffer CloneDataBuffer(DataBuffer sourceBuffer)
{
	DataBuffer newBuffer = AllocateDataBuffer(sourceBuffer.dataLength);
	
	memcpy(newBuffer.data, sourceBuffer.data, sourceBuffer.dataLength);
	
	return newBuffer;
}

void DeallocateDataBuffer(DataBufferPtr dataBuffer)
{
	free(dataBuffer->data);
	dataBuffer->dataLength = 0;
	dataBuffer->currentOffset = 0;
}